import {
	authCode2Session,
	decryptData
} from '@/api/user.js'

export default {
	data() {
		return {
			user: null, // 用户信息
			isLogin: false // 登录中
		}
	},

	watch: {
		'$store.getters.getUserInfo': {
			deep: true,
			handler(value) {
				this.user = value
			}
		}
	},

	onLoad() {
		this.user = this.$store.getters.getUserInfo
	},

	mounted() {
		this.user = this.$store.getters.getUserInfo
	},


	methods: {
		// 授权登录获取token等信息
		handleLogin(e) {
			this.isLogin = true
			// #ifdef MP-WEIXIN
			uni.login({
				provider: 'weixin',
				success: async (res) => {
					const openId = await this.handleGetOpenId(res.code)
					// uni.getUserProfile({
					// 	desc: '登录',
					// 	success: (res) => {
					// 		console.log(res)
					// 	},
					// 	fail: (error) => {
					// 		console.log(error)
					// 	}
					// })
					uni.getUserInfo({
						provider: 'weixin',
						success: (info) => { //这里请求接口
							// console.log('info', info)
							this.decryptData(openId, info)
							this.isLogin = false
						},
						fail: () => {
							this.isLogin = false
							uni.showToast({
								title: "微信登录授权失败",
								icon: "none"
							});
						}
					})
				},
				fail: () => {
					this.isLogin = false
					uni.showToast({
						title: "微信登录授权失败",
						icon: "none"
					})
				}
			})
			//#endif
		},

		// 获取openId
		async handleGetOpenId(code) {
			try {
				const {
					resultData
				} = await authCode2Session({
					data: JSON.stringify({
						code: code
					})
				})
				return resultData.openId
			} catch (error) {

			}
		},

		// 解密用户数据，存储用户数据
		async decryptData(openId, info) {
			const {
				rawData,
				signature,
				encryptedData,
				iv
			} = info

			const data = JSON.stringify({
				openId,
				rawData: JSON.parse(rawData),
				signature,
				encryptedData,
				iv
			})
			const result = await decryptData({
				data
			})
			if (result.resultCode === 0) {
				this.showLoginDialog = false
				this.user = result.resultData
				this.$store.commit('serUserInfo', result.resultData)
				this.$store.commit('setToken', result.resultData.token)
				uni.setStorageSync('user', result.resultData)
				uni.setStorageSync('token', result.resultData.token)

				try {
					this.init()
					console.log('登录')
				} catch (e) {
					this.$emit('loginSuccess', result.resultData )
				}
			}
		},
	}
}
